﻿using System;
using System.Data.Linq.Mapping;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Linq.Expressions;
using System.Runtime.Remoting.Contexts;
using SDT.DataService;

namespace SDT.DataService.Repositories
{
    public class Repository<T> : IRepository<T>,IDisposable where T : class
    {
        #region Fields
        private SystemSpiderDataContext db;
        #endregion

        #region Constructor
        public Repository()
        {
            db = new SystemSpiderDataContext();
        }
        #endregion

        #region Methods
        private Table<T> GetTable()
        {
            return db.GetTable<T>();
        }
        #endregion

        #region IRepository<T> Members
        public IQueryable<T> GetAll()
        {
            return GetTable();
        }

        public void Update(T entity)
        {
            db.Refresh(RefreshMode.KeepCurrentValues, entity);
            db.SubmitChanges();
        }
        
        public void Create(T entity)
        {
            GetTable().InsertOnSubmit(entity);
            db.SubmitChanges();
        }

        public void Delete(T entity)
        {
            if (entity == null)
                return;

            GetTable().DeleteOnSubmit(entity);
            db.SubmitChanges();
        }
        #endregion

        #region IDisposable Members

        public void Dispose()
        {           
            if (db != null)
            {
                 db.Dispose();
            }
        }

        #endregion
    }
}
